package com.maxjay.common.util.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.lowagie.text.pdf.codec.Base64;

public class SerializeUtil {

	/**
	 * 将对象存储在一个文件中
	 * 
	 * @param obj
	 * @param fileName
	 * @author:Administrator
	 */
	public static void object2File(Object obj, String fileName) {
		try {
			FileOutputStream fs = new FileOutputStream(fileName);
			ObjectOutputStream os = new ObjectOutputStream(fs);
			os.writeObject(obj);
			os.close();
			fs.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将对象从一个文件中读出
	 * 
	 * @param fileName
	 * @return
	 * @author:Administrator
	 */
	public static Object file2Object(String fileName) {
		Object obj = null;
		try {
			FileInputStream fi = new FileInputStream(fileName);
			ObjectInputStream oi = new ObjectInputStream(fi);
			obj = oi.readObject();
			fi.close();
			oi.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * 将对象序列化
	 * 
	 * @param obj
	 * @return
	 * @author:zhangliang
	 */
	public static String object2Stream(Object obj) {
		String result = null;
		try {
			java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
			java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
			oos.writeObject(obj);
			result = Base64.encodeBytes(baos.toByteArray());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	/**
	 * 反序列化
	 * 
	 * @param streamStr
	 * @return
	 * @author:Administrator
	 */
	public static Object stream2Object(String streamStr) {
		Object result = null;
		try {
			java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(Base64.decode(streamStr));
			java.io.ObjectInputStream ois = new java.io.ObjectInputStream(bais);
			result = ois.readObject();
		} catch (Exception ex2) {
			ex2.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 克隆对象
	 * 
	 * @param streamStr
	 * @return
	 * @author:Administrator
	 */
	public static Object clone(Object source) {
		Object target = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(source);
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bis);
			target = ois.readObject();
		} catch (Exception ex2) {
			ex2.printStackTrace();
		}
		return target;
	}
}
